<?php

/**
 * JingYao-backend
 *
 * @link     https://gitee.com/wang-zhihui-release/jingyao-backend
 * @apiDocument https://gitee.com/wang-zhihui-release/jingyao-backend/wikis/
 */

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Str;

class MakeFormat extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'make:format {formatName}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'create a new format class';

    /**
     * Create a new command instance.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $formatName = $this->argument('formatName');
        $camelName = ucfirst(Str::camel($formatName));
        $fileName = $camelName . 'Format.php';
        if ($this->checkExist($fileName)) {
            $this->error(sprintf('%s 已存在', $fileName));
            return 1;
        }
        $this->touchFile($fileName);
        $this->info(sprintf('%s created successfully.', $fileName));
        return 0;
    }

    private function touchFile($fileName)
    {
        $className = substr($fileName, 0, -4);
        $formatFile = fopen($this->getFormatClassPath() . '/' . $fileName, 'w');
        $fileText = <<<EOF
<?php

namespace App\\Format;

class {$className} extends Format
{
}

EOF;
        fwrite($formatFile, $fileText);
        fclose($formatFile);
        return true;
    }

    private function checkExist($fileName)
    {
        return in_array($fileName, $this->getAllFormats());
    }

    private function getAllFormats()
    {
        return scandir($this->getFormatClassPath());
    }

    private function getFormatClassPath()
    {
        return base_path() . '/app/Format';
    }
}
